#! /usr/bin/env python3
# coding: utf-8
# Filename: text2Blog.py
import sys
import text2BlogData as data
# 读取
if len(sys.argv) < 2:
    print('没有参数呀,亲!')
    exit(0)
allLines = open(sys.argv[1],encoding = 'utf-8').readlines()
rows = []
levelTable = []
floorList =[]
# 分析,预处理
for index in range(0,len(allLines)):
    if allLines[index][-1] == '\n':     #消掉换行符
        allLines[index] = allLines[index][:-1]
    line = allLines[index]
    numOfSpace = data.getNumOfSpace(line)   #得到行首空格数量
    if numOfSpace != 0:     #消掉行首空格
        allLines[index] = line[numOfSpace:]
    if data.hasNum(numOfSpace,levelTable) == False:      #当级别表中没有代表这个空格数的级别时,增加新的级别
        levelTable.append(numOfSpace)
    newRow = data.row(numOfSpace)
    rows.append(newRow)     #增加新的行数据

for aRow in rows:
    aRow.doLevel(levelTable)    #通过级别表设定行级别

for i in range(0,len(levelTable)):
    data.checkRow(0,rows,i,False,floorList)     #通过行数据,设定层级表(核心!)
# 处理
floorList.reverse()     #使层级表自底向上
for f in floorList:
    data.addTag('<li>',f,allLines)      #用<li>包住每一层
    if data.hasChild(f,rows):   #如果有子层,就用<ul>包住
        allLines[f.start] = allLines[f.start] + '<ul>'
        allLines[f.end] = allLines[f.end][:-5] + '</ul>' + allLines[f.end][-5:]     #处理标签</ul>,</li>包含关系
allLines[0] = '<ol>' + allLines[0]      #用<ol>包住整个文本
allLines[-1] = allLines[-1] + '</ol>'
# 输出
newFile = open(sys.argv[1] + '.blog',mode = 'w',encoding = 'utf-8')
for a in allLines:
    print((a))
    newFile.write(a)
newFile.close()
